// Copyright (c) 2007 Readify Pty. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.VirtualServer.Interop;
using System.Diagnostics;

namespace BuildVirtualizerProxy
{
    public class VirtualServerInterop
    {
        private static TraceSwitch m_TraceSwitch = new TraceSwitch("General", string.Empty);

        const uint EOAC_NONE = 0;
        const uint RPC_C_AUTHN_WINNT = 10;
        const uint RPC_C_AUTHZ_NONE = 0;
        const uint RPC_C_AUTHN_LEVEL_DEFAULT = 0;
        const uint RPC_C_IMP_LEVEL_IMPERSONATE = 3;

        [DllImport("Ole32.dll", CharSet = CharSet.Auto)]
        public static extern int CoSetProxyBlanket(
           IntPtr pProxy,
           uint dwAuthnSvc,
           uint dwAuthzSvc,
           uint pServerPrincName,
           uint dwAuthLevel,
           uint dwImpLevel,
           IntPtr pAuthInfo,
           uint dwCapabilities
        );

        public static int SetSecurity(object objDCOM)
        {
            IntPtr dispatchInterface = Marshal.GetIDispatchForObject(objDCOM);
            int hr = CoSetProxyBlanket(
               dispatchInterface, //pProxy
               RPC_C_AUTHN_WINNT, //dwAuthnSvc
               RPC_C_AUTHZ_NONE, //dwAuthzSvc
               0, //pServerPrincName
               RPC_C_AUTHN_LEVEL_DEFAULT, //dwAuthnLevel
               RPC_C_IMP_LEVEL_IMPERSONATE, //dwImpLevel
               IntPtr.Zero, //pAuthInfo
               EOAC_NONE //dwCapabilities
            );
            return hr;
        }

        public static void RestoreBuildMachine(string buildMachine)
        {
            try
            {
                #region Tracing
#line hidden
                if (VirtualServerInterop.m_TraceSwitch.TraceInfo)
                {
                    Trace.TraceInformation(
                        "Restoring build machine." +
                        "\nBuild Machine = '{0}'",
                        buildMachine
                        );
                }
#line default
                #endregion

                VMVirtualServerClass server = new VMVirtualServerClass();
                VMVirtualMachine machine = server.FindVirtualMachine(buildMachine);

                if (machine.State != VMVMState.vmVMState_Saved)
                {
                    throw new Exception("The build machine was not in a saved state! Bad.");
                }

                IVMTask startupTask = machine.Startup();
                startupTask.WaitForCompletion(60000);

                if (!startupTask.IsComplete)
                {
                    throw new Exception("Timed out waiting for restore to complete!");
                }

                #region Tracing
#line hidden
                if (VirtualServerInterop.m_TraceSwitch.TraceInfo)
                {
                    Trace.TraceInformation(
                        "Build machine was successfully restored." +
                        "\nBuild Machine = '{0}'",
                        buildMachine
                        );
                }
#line default
                #endregion
            }
            catch (Exception ex)
            {
                #region Tracing
#line hidden
                if (VirtualServerInterop.m_TraceSwitch.TraceError)
                {
                    Trace.TraceError(
                        "The following error occured waiting to restore from saved state:" +
                        "\nBuild Machine = '{0}'" +
                        "\nException = '{1}'",
                        buildMachine,
                        ex
                        );
                }
#line default
                #endregion

                throw ex;
            }
        }

        public static void SaveBuildMachine(string buildMachine, bool shouldBeRunning)
        {
            try
            {
                #region Tracing
#line hidden
                if (VirtualServerInterop.m_TraceSwitch.TraceInfo)
                {
                    Trace.TraceInformation(
                        "Saving build machine." +
                        "\nBuild Machine = '{0}'",
                        buildMachine
                        );
                }
#line default
                #endregion

                VMVirtualServerClass server = new VMVirtualServerClass();
                VMVirtualMachine machine = server.FindVirtualMachine(buildMachine);

                if (machine.State == VMVMState.vmVMState_Saved)
                {
                    #region Tracing
#line hidden
                    if (VirtualServerInterop.m_TraceSwitch.TraceInfo)
                    {
                        Trace.TraceInformation(
                            "Build machine was already saved (good)." +
                            "\nBuild Machine = '{0}'",
                            buildMachine
                            );
                    }
#line default
                    #endregion

                    return;
                }

                #region Tracing
#line hidden
                if (VirtualServerInterop.m_TraceSwitch.TraceWarning && !shouldBeRunning)
                {
                    Trace.TraceWarning(
                        "Build machine was left running. Will now save." +
                        "\nBuild Machine = '{0}'",
                        buildMachine
                        );
                }
#line default
                #endregion

                IVMTask saveTask = machine.Save();
                saveTask.WaitForCompletion(60000);

                if (!saveTask.IsComplete)
                {
                    throw new Exception("Timed out waiting for save to complete!");
                }

                #region Tracing
#line hidden
                if (VirtualServerInterop.m_TraceSwitch.TraceInfo)
                {
                    Trace.TraceInformation(
                        "Build machine was successfully saved." +
                        "\nBuild Machine = '{0}'",
                        buildMachine
                        );
                }
#line default
                #endregion
            }
            catch (Exception ex)
            {
                #region Tracing
#line hidden
                if (VirtualServerInterop.m_TraceSwitch.TraceError)
                {
                    Trace.TraceError(
                        "The following error occured waiting to save state:" +
                        "\nBuild Machine = '{0}'" +
                        "\nException = '{1}'",
                        buildMachine,
                        ex
                        );
                }
#line default
                #endregion

                throw ex;
            }
        }
    }
}
